﻿#region  文件信息
// ---------------------------------------------------------------------------------------
// <copyright file="Common.cs" company="">
// 作者：李帅伦
// </copyright>
// <summary>
// 类型简介：
// 类型详细：Common.cs
// 创建时间：2015-01-04 20:59
// 修改时间：2015-01-04 20:59
// </summary>
// ---------------------------------------------------------------------------------------
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.International.Converters.PinYinConverter;

namespace WebCommon.Com
{
    /// <summary>
    /// 静态通用
    /// </summary>
    public class Static
    {
        /// <summary>
        /// URL转议
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string UrlEncode(string url)
        {
            return System.Web.HttpUtility.UrlEncode(url);
        }

        /// <summary>
        /// url转义（大写）
        /// </summary>
        /// <param name="str"></param>
        /// <param name="daxie">大写</param>
        /// <returns></returns>
        public static string UrlencodeToUpper(string str, bool daxie = true)
        {
            var sb = new StringBuilder();
            foreach (var c in str)
            {
                string urlEncode = HttpUtility.UrlEncode(c.ToString());
                if (urlEncode != null && urlEncode.Length > 1)
                {
                    var ue = daxie ? urlEncode.ToUpper() : urlEncode.ToLower();
                    sb.Append(ue);
                }
                else
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获取拼音全部
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetPinyin(string str)
        {
            string r = string.Empty;
            foreach (var obj in str)
            {
                try
                {
                    var chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0];
                    r += t.Substring(0, t.Length - 1);
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }

        /// <summary>
        /// 获取拼音首字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetFirstPinyin(string str)
        {
            string r = string.Empty;
            foreach (var obj in str)
            {
                try
                {
                    var chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0];
                    r += t.Substring(0, 1);
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }
        /// <summary>
        /// Linux时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        /// <summary>
        /// Linux时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp(int x)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds / x).ToString();
        }

        /// <summary>
        /// 转成XML
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string ParseXml(SortedDictionary<string, string> parameters)
        {

            var sb = new StringBuilder();
            sb.Append("<xml>");
            var akeys = new ArrayList(parameters.Keys);
            foreach (string k in akeys)
            {
                var v = (string)parameters[k];
                if (Regex.IsMatch(v, @"^[0-9.]$"))
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }
        /// <summary>
        /// 转成XML
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string ParseXml(Dictionary<string, string> parameters)
        {

            var sb = new StringBuilder();
            sb.Append("<xml>");
            var akeys = new ArrayList(parameters.Keys);
            foreach (string k in akeys)
            {
                var v = (string)parameters[k];
                if (Regex.IsMatch(v, @"^[0-9.]$"))
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }
        #region Public Methods and Operators

        /// <summary>
        /// 对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1& key2=value2…）拼接成字符串string。
        /// </summary>
        /// <param name="dictionary">
        /// The dictionary.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetOrderBy(IEnumerable<KeyValuePair<string, string>> dictionary)
        {
            var dy = dictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);

            List<string> strings = new List<string>();
            foreach (var item in dy)
            {
                strings.Add(item.Key + "=" + item.Value);
            }

            string join = string.Join("&", strings);

            return join;
        }



        /// <summary>
        /// 用于完整编码
        /// </summary>
        /// <param name="dictionary">
        /// The dictionary.
        /// </param>
        /// <param name="daxie">大写</param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetUrlencode(IEnumerable<KeyValuePair<string, string>> dictionary, bool daxie = true)
        {
            var dy = dictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);

            List<string> strings = new List<string>();
            foreach (var item in dy)
            {
                strings.Add(item.Key + "=" + Static.UrlencodeToUpper(item.Value, daxie));
            }
            string join = string.Join("&", strings);

            return join;
        }

        ///// <summary>
        ///// 用于url拼接编码
        ///// </summary>
        ///// <param name="dictionary">
        ///// The dictionary.
        ///// </param>
        ///// <param name="daxie">大写</param>
        ///// <returns>
        ///// The <see cref="string"/>.
        ///// </returns>
        //public static string GetUrlencodeComponent(IEnumerable<KeyValuePair<string, string>> dictionary, bool daxie = true)
        //{
        //    var dy = dictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);

        //    List<string> strings = new List<string>();
        //    foreach (var item in dy)
        //    {
        //        strings.Add(item.Key + "=" + Static.UrlencodeToUpper(item.Value, daxie));
        //    }

        //    string join = string.Join("&", strings);

        //    return join;
        //}
        /// <summary>
        /// 父类赋值给子类
        /// </summary>
        /// <typeparam name="T">父类</typeparam>
        /// <typeparam name="TU">子类</typeparam>
        /// <param name="parent">模型</param>
        /// <returns></returns>
        public static TU ParentToSub<T, TU>(T parent)
            where TU : class, T, new()
        {
            TU tu = new TU();
            var t = typeof(T);
            var tp = t.GetProperties();
            foreach (var item in tp)
            {
                if (item.CanRead && item.CanWrite)
                {
                    item.SetValue(tu, item.GetValue(parent, null), null);
                }
            }


            return tu;
        }


        /// <summary>
        /// Base64ToString
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string Base64ToString(string txt)
        {
            try
            {
                byte[] bpath = Convert.FromBase64String(txt);
                return Encoding.UTF8.GetString(bpath);
            }
            catch (Exception)
            {

                return String.Empty;
            }





        }
        /// <summary>
        /// StringToBase64
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string StringToBase64(string txt)
        {
            try
            {
                byte[] bytedata = Encoding.UTF8.GetBytes(txt);
                return Convert.ToBase64String(bytedata, 0, bytedata.Length);
            }
            catch (Exception)
            {

                return String.Empty;

            }
            ;
        }

        /// <summary>
        /// 获取模型的 属性名和属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static IEnumerable<KeyValuePair<string, string>> GetNoBaseObjNameValue(object obj, bool addNull = false)
        {
            Type type = obj.GetType();
            var sd = new SortedDictionary<string, string>();
            foreach (var item in type.GetProperties())
            {

                if (item.DeclaringType != null && item.DeclaringType.Name == type.Name)
                {
                    var value = item.GetValue(obj, null);
                    if (value == null)
                    {
                        if (addNull)
                        {
                            sd.Add(item.Name, "");
                        }
                    }
                    else
                    {
                        sd.Add(item.Name, value.ToString());
                    }
                }

            }
            return sd;

        }

        /// <summary>
        /// 获取模型的 属性名和属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="addNull">添加空值</param>
        /// <param name="strs">过滤字符串</param>
        /// <returns></returns>
        public static IEnumerable<KeyValuePair<string, string>> GetObjNameValue(object obj, bool addNull, params string[] strs)
        {
            Type type = obj.GetType();
            var sd = new SortedDictionary<string, string>();
            foreach (var item in type.GetProperties())
            {

                if (strs.Any(a => item.DeclaringType != null && item.DeclaringType.Name != a))
                {
                    var value = item.GetValue(obj, null);
                    if (value == null)
                    {
                        if (addNull)
                        {
                            sd.Add(item.Name, "");
                        }
                    }
                    else
                    {
                        sd.Add(item.Name, value.ToString());
                    }
                }

            }
            return sd;

        }



        /// <summary>
        /// 获取模型的 属性名和属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="addNull">添加空值</param>
        /// <returns></returns>
        public static IEnumerable<KeyValuePair<string, string>> GetObjNameValue(object obj, bool addNull = false)
        {
            Type type = obj.GetType();
            var sd = new SortedDictionary<string, string>();
            foreach (var item in type.GetProperties())
            {
                var value = item.GetValue(obj, null);

                if (value == null)
                {
                    if (addNull)
                    {
                        sd.Add(item.Name, "");
                    }
                }
                else
                {
                    sd.Add(item.Name, value.ToString());
                }

            }
            return sd;
        }

        /// <summary>
        /// 时间转换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime YyyyMMddHHmmssToDateTime(string str)
        {
            return DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
        }
        /// <summary>
        /// 时间转换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime YyyyMMddHHmmToDateTime(string str)
        {
            return DateTime.ParseExact(str, "yyyyMMddHHmm", CultureInfo.CurrentCulture);
        }
        /// <summary>
        /// 时间转换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime YyyyMMddToDateTime(string str)
        {
            return DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture);
        } /// <summary>
          /// 时间转换
          /// </summary>
          /// <param name="str"></param>
          /// <returns></returns>
        public static DateTime HHmmssToDateTime(string str)
        {
            return DateTime.ParseExact(str, "HHmmss", CultureInfo.CurrentCulture);
        }

        /// <summary>
        /// 方法写入模型
        /// </summary>
        /// <typeparam name="I"></typeparam>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="obj2"></param>
        /// <param name="func">赋值条件</param>
        public static void InterfaceSetModel<I, T>(I obj, ref T obj2)
        {
            Type t1 = typeof(I);
            Type t2 = obj2.GetType();
            var propertyInfos2 = t2.GetProperties();

            foreach (var prop2 in propertyInfos2)
            {
                var met = t1.GetMethod("Get" + prop2.Name);
                if (met == null)
                {
                    continue;
                }

                var val = met.Invoke(obj, null);
                if (val == null)
                {
                    continue;
                }

                if (prop2.PropertyType.Name.Contains("String"))
                {
                    prop2.SetValue(obj2, val.ToString(), null);
                    continue;
                }

                prop2.SetValue(obj2, val, null);



            }
        }

        /// <summary>
        /// 方法写入模型
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="obj2"></param>
        public static void ModelSetModel<U, T>(U obj, ref T obj2)
        {
            Type t1 = typeof(U);
            Type t2 = obj2.GetType();
            var propertyInfos2 = t2.GetProperties();

            foreach (var prop2 in propertyInfos2)
            {
                var met = t1.GetProperty(prop2.Name);
                if (met == null)
                {
                    continue;
                } 
                var val = met.GetValue(obj, null);
                if (val == null)
                {
                    continue;
                }
                if (prop2.PropertyType.Name.Contains("String"))
                {
                    prop2.SetValue(obj2, val.ToString(), null);
                    continue;
                }
                prop2.SetValue(obj2, val, null);
            }
        }
        #endregion

    }
}